package rabbitMqLearn.mq.work_model.consumer;

import com.rabbitmq.client.*;
import rabbitMqLearn.mq.config.Config;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class RPEConsumer {
    public static void main(String[] args) throws IOException, TimeoutException {
        RPEConsumer consumer = new RPEConsumer();
        consumer.rpc();
    }

    void rpc() throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(Config.HOST);
        factory.setPort(Config.PORT);
        factory.setVirtualHost(Config.VIRTUALHOST);
        factory.setUsername(Config.USERNAME);
        factory.setPassword(Config.PASSWORD);

        Connection connection = factory.newConnection();

        Channel channel = connection.createChannel();

        //声明队列
        channel.queueDeclare(Config.RPC_REQUEST_QUEUE, true, false, false, null);
        channel.queueDeclare(Config.RPC_RESPONSE_QUEUE, true, false, false, null);

        channel.basicQos(1);

        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String message = new String(body, "UTF-8");
                System.out.println("收到请求 " + message);
                String ret = "成功处理请求：" + message;

                //发送给response
                AMQP.BasicProperties properties1 = new AMQP.BasicProperties().builder()
                        .correlationId(properties.getCorrelationId())
                        .build();
                channel.basicPublish("", properties.getReplyTo(), properties1, ret.getBytes());

                /**
                 * long deliveryTag, 确认id
                 * boolean multiple 是否批量确认
                 */
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        };
        //接受消息
        channel.basicConsume(Config.RPC_REQUEST_QUEUE, false, consumer);
    }


}
